/**
 * The Community Project
 * Copyright Team1 Productions
 * 
 * Joshua Amick
 * Stephen Cunningham
 * Thema Davis
 * Tomika Dawson
 * Lucie DeCristofaro
 * 
 * All Rights Reserved.
 */

package com.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.domain.User;
import com.forms.SaveUserRequestForm;
import com.util.CommunityEmailer;

public class SaveUserRequestAction extends CommunityBaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.execute(mapping, form, request, response);
		
		CommunityEmailer comEmail = new CommunityEmailer();

		SaveUserRequestForm f = (SaveUserRequestForm) form;
		ActionForward forward;
		if ((f.getUsername()!=null&&f.getUsername().length()>0)&&
				(f.getPassword1()!=null&&f.getPassword1().length()>0)&&
				(f.getEmail()!=null&&f.getEmail().length()>0)){
			if(f.getPassword1().equals(f.getPassword2())){
				if(f.getEmail().matches("(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*")){
					User checkUser = this.biz.getPrivateMgr().getUserDAO().getUserByUsername(f.getUsername());
					if(checkUser==null){
						User newUser = this.biz.getPrivateMgr().saveUserInitial(f.getUsername(),f.getPassword1(),f.getEmail(),false);
						if(newUser!=null&&newUser.getKeyId()>0){
							request.setAttribute("INFO", "User saved successfully.");
							forward = mapping.findForward("success");
						}
						else{
							request.setAttribute("ERRORS", "Error occurred while saving user.");
							forward = mapping.findForward("failure");
						}
					}
					else{
						request.setAttribute("ERRORS", "Username already taken.  Choose another one.");
						forward = mapping.findForward("failure");
					}
				}
				else{
					request.setAttribute("ERRORS", "Error: invalid email address.");
					forward = mapping.findForward("failure");
				}
			}
			else{
				request.setAttribute("ERRORS", "Error: password and confirmation password did not match.");
				forward = mapping.findForward("failure");
			}
		}
		else{
			request.setAttribute("ERRORS", "Error: Please fill out all required fields.");
			forward = mapping.findForward("failure");
		}
		

		return forward;
	}
}
